package net.j4love.io;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @author He Peng
 * @create 2017-08-05 22:26
 * @update 2017-08-05 22:26
 * @updatedesc : 更新说明
 * @see
 */
public class SyncBlockingIOEchoServer {

    public static void main(String[] args) throws IOException {
        new SyncBlockingIOEchoServer().start("127.0.0.1",8080);
    }

    public void start(String host,int port) throws IOException {
        ServerSocket serverSocket = new ServerSocket();
        serverSocket.bind(new InetSocketAddress(host,port));
        System.out.println("echo server started on " + host + ":" + port);
        for (;;) {
            Socket socket = serverSocket.accept();
            InputStream inputStream = socket.getInputStream();
            BufferedReader bufReader = new BufferedReader(
                    new InputStreamReader(inputStream, "UTF-8"));
            String line = bufReader.readLine();
            String body = line == null ? "" : line;
            System.out.println("Received client data : " + body);
            OutputStream outputStream = socket.getOutputStream();
            PrintWriter writer = new PrintWriter(outputStream);
            writer.write(body);
            writer.flush();
            socket.close();
        }
    }
}
